$().ready(function(){
    var uploader = '../js-plugin/uploadify/uploadify_cn.swf';
    var images_script = "/action/master/AdsFileUpload";
    var cancelImg = '../js-plugin/uploadify/cancel.png';
    var folder = '/upload';
    $('#ads_file').uploadify({
        'uploader': uploader,
        'script': images_script,
        'cancelImg': cancelImg,
        'folder': folder,
        'auto': true,
        'multi': false,
        'fileExt': '*.jpg;*.gif;*.png;*.bmp;*.swf',
        'fileDesc': '请选择广告文件 (.JPG, .GIF, .PNG, .BMP, .SWF)',
        'queueID': 'custom-queue',
        'buttonText': "选择上传文件",
        'removeCompleted': true,
        'onComplete': function(e, queueId, fileObj, response, data){
            //console.log(response);
            var obj = $.parseJSON(response);
            if (obj.success) {
                $(".loadingbox").empty();
                $(".loadingbox").append(loadingTpl, {
                    icoType: "succ",
                    loadIcon: "",
                    msgHtml: "文件上传成功"
                });
                $(".loadingbox").fadeIn(50);
                $(".loadingbox").delay(2000).fadeOut(600);
                $("#view_body").text("");
                if ($("#ads_view").length < 1) {
                    $("#view_body").append("<p id=\"ads_view\"></p>");
                }
                //console.log(fileObj.type == ".swf");
                if (fileObj.type == ".swf") {
                    var params = {
                        scale: "exactFit"
                    };
                    swfobject.embedSWF(obj.filepath, "ads_view", "100%", "100", "9.0.115", "/../js-plugin/uploadify/expressInstall.swf", "", params);
                }
                else {
                    $("#view_body").html("<img src=\"" + obj.filepath + "\" width=\"100%\" height=\"100px\" />");
                }
                $("#midea").val(fileObj.type);
                $("#files").val(obj.filepath);
            }
            else {
                $(".loadingbox").empty();
                $(".loadingbox").append(loadingTpl, {
                    icoType: 'fail',
                    loadIcon: '',
                    msgHtml: obj.message
                });
                $(".loadingbox").delay(3000).fadeOut(600);
                $('#status-message').append("<li>" + obj.message + "</li>");
            }
        }
    });
    
    $("#startdate").datepicker({
        dateFormat: 'yy-mm-dd'
    }).attr("readonly", true);
    $("#enddate").datepicker({
        dateFormat: 'yy-mm-dd'
    }).attr("readonly", true);
    
    $(".saveBtn").click(function(){
        $("#adsEditor").submit();
        return false;
    });
    // 中文字两个字节       
    jQuery.validator.addMethod("byteRangeLength", function(value, element, param){
        var length = value.length;
        for (var i = 0; i < value.length; i++) {
            if (value.charCodeAt(i) > 127) {
                length++;
            }
        }
        return this.optional(element) ||
        (length >= param[0] && length <= param[1]);
    }, "请确保输入的值在3-15个字节之间(一个中文字算2个字节)");
    jQuery.validator.addMethod("isDate", function(value, element){
        var ereg = /^(\d{1,4})(-|\/)(\d{1,2})(-|\/)(\d{1,2})$/;
        var r = value.match(ereg);
        if (r == null) {
            return false;
        }
        var d = new Date(r[1], r[3] - 1, r[5]);
        var result = (d.getFullYear() == r[1] && (d.getMonth() + 1) == r[3] && d.getDate() == r[5]);
        return this.optional(element) || (result);
    }, "请输入正确的日期");
    $("#adsEditor").validate({
        submitHandler: function(form){
            $(form).ajaxSubmit({
                target: "#errormsg",
                dataType: "json",
                beforeSubmit: function(){
                    $(".loadingbox").append(loadingTpl, {
                        icoType: 'clear',
                        loadIcon: '<img src=\"/images/manage/loading002.gif\">',
                        msgHtml: '正在提交数据，请稍候...'
                    });
                    $(".loading").fadeIn(50);
                },
                success: function(data){
                    if (!data.success) {
                        //$("#errormsg").text(data.message);
                        //$(".post-state").removeClass("success").addClass("error").fadeTo("slow", 1).fadeIn(400).delay(4000).slideUp(400);
                        $(".loadingbox").empty();
                        $(".loadingbox").append(loadingTpl, {
                            icoType: 'fail',
                            loadIcon: '',
                            msgHtml: data.message
                        });
                        $(".loadingbox").delay(3000).fadeOut(600);
                    }
                    else {
                        //$("#errormsg").text(data.message);
                        //$(".post-state").removeClass("error").addClass("success").fadeTo("slow", 1).fadeIn(400).delay(4000).slideUp(400);
                        $(".loadingbox").empty();
                        $(".loadingbox").append(loadingTpl, {
                            icoType: "succ",
                            loadIcon: "",
                            msgHtml: data.message
                        });
                        $(".loadingbox").fadeIn(50);
                        $(".loadingbox").delay(2000).fadeOut(600);
                    }
                    
                }
            });
        },
        rules: {
            name: {
                required: true,
                byteRangeLength: [4, 200]
            },
            url: {
                url: true
            },
            startdate: {
                required: true,
                isDate: true
            },
            enddate: {
                required: true,
                isDate: true
            },
            files: {
                required: true
            }
        },
        messages: {
            name: {
                required: "请填写广告名称",
                byteRangeLength: "广告名称名称必须在4-200个字符之间(一个中文字算2个字符)"
            },
            url: {
                url: "链接地址格式错误"
            },
            startdate: {
                required: "请选择广告发布时间",
                isDate: "发布时间格式错误"
            },
            enddate: {
                required: "请填写广告停止发布的时间",
                isDate: "广告结束时间格式错误"
            },
            files: {
                required: "请上传广告文件"
            }
        }
    });
});
